package com.cooper.mediadb;

import java.util.List;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Toast;

import com.cooper.android.comm.AppDownloadTask;
import com.cooper.scrapemedialib.R;
import com.cooper.slidingmenu.utils.ConfirmDialog;
import com.cooper.slidingmenu.utils.SingleFragmentContain;
import com.cooper.slidingmenu.utils.ConfirmDialog.ConfirmDialogListener;
import com.cooper.slidingmenu.utils.FullWatiDialog.FullWatiDialogListener;
import com.cooper.slidingmenu.utils.SampleInputDialog.SampleInputDialogListener;
import com.cooper.slidingmenu.utils.SampleItemSelectDialog.SampleItemSelectDialogListener;
import com.slidingmenu.lib.app.SlidingFragmentActivity;

public class MediaMainActivity extends SlidingFragmentActivity implements
		SingleFragmentContain, SampleItemSelectDialogListener,
		ConfirmDialogListener, FullWatiDialogListener,
		SampleInputDialogListener {
	

	public static boolean showOffer;
	public static final String MXVP = "com.mxtech.videoplayer.ad";

	public static final int CONFIRM_USE_NET_DIALOG = 11;

	protected Fragment mContent;
	
	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
	
		if (keyCode == KeyEvent.KEYCODE_BACK) {

			if (getSlidingMenu().isMenuShowing()) {
				finish();
			} else {
				getSlidingMenu().toggle();
			}
			return true;
		}
		if (keyCode == KeyEvent.KEYCODE_MENU){
			getSlidingMenu().toggle();
			return true;
		}
		return super.onKeyUp(keyCode, event);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.d("MediaMainActivity", "call onCreate:" + this);
		if (savedInstanceState != null) {
			Log.d("MediaMainActivity", "load context from savedInstanceState");
			mContent = getSupportFragmentManager().getFragment(
					savedInstanceState, "mContent");
		}
	}

	@Override
	public void showNavigation() {
		getSlidingMenu().toggle();
	}

	@Override
	public Fragment getCurFragment() {
		return mContent;
	}

	public MediaBrowseBaseFragment<?> getCurMediaControlFragment() {
		return (MediaBrowseBaseFragment<?>) mContent;
	}

	@Override
	public void onSampleItemsSelectDialogReturn(int which, int selectWhich) {
		((SampleItemSelectDialogListener) mContent)
				.onSampleItemsSelectDialogReturn(which, selectWhich);
	}

	public void mediaPlayResult(Uri uri, int position) {
		getCurMediaControlFragment().onMediaPlayResult(uri, position);
	}

	@Override
	public void onConfirmDialogReturn(int which, boolean isOk) {
		switch (which) {
		case CONFIRM_USE_NET_DIALOG:
			if (isOk) {
				switchContent(preContent);
			} else {
				preContent = null;
			}
			break;
		default:
			((ConfirmDialogListener) mContent).onConfirmDialogReturn(which,
					isOk);
		}
	}

	@Override
	public void onFullWatingCanceled() {
		((FullWatiDialogListener) mContent).onFullWatingCanceled();
	}

	@Override
	public void onSampleInputDialogReturn(int which, boolean isOk, String text) {

		getCurMediaControlFragment().onSampleInputDialogReturn(which, isOk,
				text);
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		Log.d("MediaMainActivity", "call onSaveInstanceState");
		try {
			if (mContent != null)
				getSupportFragmentManager().putFragment(outState, "mContent",
						mContent);
		} catch (Exception e) {
			Log.e("MediaMainActivity", e.getMessage(), e);
		}
	}

	public void switchContent(Fragment fragment) {
		if (fragment instanceof DialogFragment) {
			((DialogFragment) fragment).show(getSupportFragmentManager(),
					"SWITCH_CONTENT_DIALOG");
		} else {
			mContent = fragment;
			FragmentTransaction tans = getSupportFragmentManager()
					.beginTransaction();

			tans.replace(R.id.content_frame, fragment);
			tans.commit();
			getSlidingMenu().showContent();
		}
	}

	public static final String MXVP_PRO = "com.mxtech.videoplayer.pro";
	public static final String GOOGLE_PLAY_OLD = "com.google.market";
	public static final String GOOGLE_PLAY_NEW = "com.android.vending";
	public static final String RESULT_VIEW = "com.mxtech.intent.result.VIEW";
	public static final String EXTRA_DECODE_MODE = "decode_mode";
	public static final String EXTRA_FAST_MODE = "fast_mode";
	public static final String EXTRA_VIDEO_LIST = "video_list";
	public static final String EXTRA_SUBTITLES = "subs";
	public static final String EXTRA_SUBTITLES_ENABLE = "subs.enable";
	public static final String EXTRA_TITLE = "title";
	public static final String EXTRA_POSITION = "position";
	public static final String EXTRA_RETURN_RESULT = "return_result";
	private static final int PLAYER_RQUESTE_CODE_PRO = 1001;
	private static final int PLAYER_RQUESTE_CODE_AD = 1002;

	public void playMedia(List<Uri> uris, String title, Uri uri, int position) {
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setDataAndType(uri, "video/*");
		if (uris.size() > 1) {
			Parcelable[] playList = uris.toArray(new Parcelable[uris.size()]);

			intent.putExtra(EXTRA_VIDEO_LIST, playList);
		}
		intent.putExtra(EXTRA_POSITION, position);
		callMXPlayer(intent, title);
	}

	public void playMedia(List<Uri> uris, String title) {
		if (uris == null || uris.isEmpty()) {
			Toast.makeText(this, R.string.media_uri_error, Toast.LENGTH_LONG)
					.show();
			mediaPlayResult(null, -1);
			return;
		}
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setDataAndType(uris.get(0), "video/*");

		// s/w decoder 软/硬 解
		// i.putExtra( EXTRA_DECODE_MODE, (byte)1 );

		// fast mode 快速 软解
		// i.putExtra( EXTRA_FAST_MODE, true );

		if (uris.size() > 1) {
			Parcelable[] playList = uris.toArray(new Parcelable[uris.size()]);

			intent.putExtra(EXTRA_VIDEO_LIST, playList);
		}
		// i.putExtra( EXTRA_VIDEO_LIST, new Parcelable[] { videoUri, Uri.parse(
		// "file:///mnt/sdcard/Movies/747a.3gp") } );

		// with a subtitle. 字幕
		// i.putExtra( EXTRA_SUBTITLES, new Parcelable[] { subtitleUri1,
		// subtitleUri2 } );

		// explictly select first subtitle. 开启外部字幕
		// i.putExtra( EXTRA_SUBTITLES_ENABLE, new Parcelable[] { subtitleUri1 }
		// );
		// if (uris.get(0).)
		// MX PLAYER Have a Bug net video cant position

		if ("file".equals(uris.get(0).getScheme().trim().toLowerCase())) {
			intent.putExtra(EXTRA_POSITION, 10);
			Log.d("MediaControlActivity", "Position to 10");
		}
		// starting from 10s. 播放跳转
		// intent.putExtra(EXTRA_POSITION, 250);

		callMXPlayer(intent, title);
	}

	private void callMXPlayer(Intent i, String title) {
		// provides title text.
		i.putExtra(EXTRA_TITLE, getResources().getString(R.string.app_name)
				+ "-" + title);

		// request result
		i.putExtra(EXTRA_RETURN_RESULT, true);
		// playerProInstalled = true;
		// playerADInstalled = false;

		PackageInfo packageInfo = null;
		try {
			packageInfo = getPackageManager().getPackageInfo(MXVP_PRO, 0);
		} catch (NameNotFoundException e1) {
			try {
				packageInfo = getPackageManager().getPackageInfo(MXVP, 0);
			} catch (NameNotFoundException e2) {
				packageInfo = null;
			}
		}

		if (packageInfo != null) {

			// if (packageInfo.versionCode < ?) Toast.makeText(this,
			// R.string.mx_player_version_error_msg,Toast.LENGTH_LONG).show();
			i.setPackage(packageInfo.packageName);
			this.startActivityForResult(i, PLAYER_RQUESTE_CODE_PRO);

		} else {
			new PlayNotInstallDialog().show(getSupportFragmentManager(),
					"play_not_install_Dialog");
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		Log.d("MediaControlActivity", "rqc:" + requestCode);
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == PLAYER_RQUESTE_CODE_PRO
				|| requestCode == PLAYER_RQUESTE_CODE_AD) {
			if (resultCode == RESULT_OK && data != null) {
				Log.d("MediaControlActivity", "result ok!");
				Uri lastVideoUri = data.getData();
				int lastPosition = data.getIntExtra(EXTRA_POSITION, 0);
				mediaPlayResult(lastVideoUri, lastPosition);
			} else {
				Log.d("MediaControlActivity", "result not ok!" + data + "|"
						+ resultCode);
				mediaPlayResult(null, -1);
			}
		}
	}

	public static class PlayNotInstallDialog extends DialogFragment {

		// private static final String DOWNLOADS_TAG = "downloads";
		// private static final String DOWNLOAD_TAG = "download";
		private static final String DOWNLOAD_MXPLAYER = "mxplayer";

		private static final String PLAYER_INFO_URL = "http://cooper-media-database.googlecode.com/svn/plug/info.xml";

		@Override
		public Dialog onCreateDialog(Bundle savedInstanceState) {
			// http://apk.gfan.com/Product/App162286.html

			AlertDialog.Builder result = new AlertDialog.Builder(getActivity())
					.setIcon(R.drawable.ic_dialog_icon)
					.setTitle(R.string.player_not_install_title)
					.setMessage(R.string.player_not_install)

					.setPositiveButton(R.string.install_player,
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									Intent intent = new Intent(
											Intent.ACTION_VIEW,
											Uri.parse("market://search?q=pname:"
													+ MXVP));

									PackageInfo packageInfo = null;
									try {
										packageInfo = getActivity()
												.getPackageManager()
												.getPackageInfo(
														GOOGLE_PLAY_NEW, 0);
									} catch (NameNotFoundException e1) {
										try {
											packageInfo = getActivity()
													.getPackageManager()
													.getPackageInfo(
															GOOGLE_PLAY_OLD, 0);
										} catch (NameNotFoundException e2) {
											packageInfo = null;
										}
									}

									if (packageInfo != null) {
										intent.setPackage(packageInfo.packageName);
										Log.d("MainActivity", "setPackage");
									}

									try {
										startActivity(intent);
									} catch (ActivityNotFoundException e2) {
										Toast.makeText(getActivity(),
												R.string.not_install_market,
												Toast.LENGTH_LONG).show();
									}

								}
							})
					.setNegativeButton(R.string.alert_dialog_cancel, null);

			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
				result.setNeutralButton(R.string.install_default_player,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								new AppDownloadTask(getActivity()
										.getApplicationContext(),
										PLAYER_INFO_URL)
										.execute(DOWNLOAD_MXPLAYER);

							}
						});
			}

			return result.create();
		}
	}

	public MediaMainActivity() {
		super();
	}

	private Fragment preContent = null;

	public void switchNetContent(Fragment fragment) {
		preContent = fragment;
		ConfirmDialog.newInstance(CONFIRM_USE_NET_DIALOG,
				getResources().getString(R.string.app_name),
				getResources().getString(R.string.not_wifi_net_access)).show(
				getSupportFragmentManager(), "NET_ACCESS_CONFIRM");
	}

}